package com.rongzhe.house.presenter;

import android.content.Intent;
import android.text.TextUtils;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.rongzhe.house.manager.UserManager;
import com.rongzhe.house.ui.UiControlInterface;
import com.rongzhe.house.ui.activity.H5BaseActivity;
import com.rongzhe.house.utils.MD5Util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by yadong on 2017/5/24.
 */

/**
 * 提供H5 , js访问接口.
 */
public class H5Presenter extends BasePresenter {
    private static final String GET_LOGIN_SESSION = "jsbridge_get_login_session";

    private Map<String, BridgeHandler> mAllActionHandlers = new HashMap<>();
    private String mCurrentUrl;

    public H5Presenter(UiControlInterface uiControlInterface) {
        super(uiControlInterface);
        mAllActionHandlers.put(GET_LOGIN_SESSION, getLoginSession);
    }

    @Override
    public void start(Intent intent) {
        String url = ((H5BaseActivity)getUiControlInterface()).getUrl();
        if (TextUtils.isEmpty(mCurrentUrl)) {
            doLoadUrl(url);
        }
    }

    public void configWebView(BridgeWebView webView) {
        Set<Map.Entry<String, BridgeHandler>> allHandlers
                = mAllActionHandlers.entrySet();
        for (Map.Entry<String, BridgeHandler> handlerItem : allHandlers) {
            webView.registerHandler(handlerItem.getKey(), handlerItem.getValue());
        }
    }

    protected void doLoadUrl(String url) {
        ((H5BaseActivity)getUiControlInterface()).loadUrl(url);
        this.mCurrentUrl = url;
    }

    private BridgeHandler getLoginSession = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            function.onCallBack(MD5Util.base64encode(UserManager.getInstance().getUserToken()));
        }
    };


}
